import axios from 'axios';
import COS from 'cos-js-sdk-v5';
import { message } from 'ant-design-vue';
import { v4 as uuid } from 'uuid';

export default class HSUploader {
  constructor() {
    this.getSecretIdUrl = 'http://42.193.106.22/pisces/tool/cos_tmp_key';
  }

  async upload(blob, callback) {
    try {
      // 获取临时密钥
      const { code, data, message:msg } = await this.getTempCredentials();
      if (code !== 200) {
        message.error(msg);
        return;
      }

      // 初始化COS对象
      const cos = new COS({
        getAuthorization: function (options, callback) {
          // 直接使用临时密钥进行签名返回
          callback({
            TmpSecretId: data?.tmp_key?._Credentials?._TmpSecretId,
            TmpSecretKey: data?.tmp_key?._Credentials?._TmpSecretKey,
            XCosSecurityToken: data?.tmp_key?._Credentials?._Token,
            ExpiredTime: data?.tmp_key?._ExpiredTime
          });
        },
      });
      // 生成上传到COS的文件路径
      const cosPath = `/hs-uploads/web/${uuid()}`;
      // 执行上传
      cos.putObject({
        Bucket: data?.voice_bucket,
        Region: data?.region,
        Key: cosPath,
        StorageClass: 'STANDARD',
        Body: blob,
        onProgress: function(progressData) {
          console.log(JSON.stringify(progressData));
        }
      }, function(err, data) {
        if (err) {
          console.error('上传失败：', err);
          callback(null, err);
        } else {
          console.log('上传成功：', data);
          const url = `https://${data.Location}`;
          callback(url); // 上传成功，返回文件 URL
        }
      });
    } catch (error) {
      console.error('获取临时密钥失败', error);
      callback(null, error);
    }
  }

  // 获取临时密钥的方法
  async getTempCredentials() {
    const response = await axios.get(this.getSecretIdUrl);
    if (response.status === 200 && response.data) {
      return response.data;
    } else {
      throw new Error('Unable to get temporary credentials');
    }
  }
}